package struts3.util;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

import struts3.form.XmlBean;

public class Struts_Config {

	public Struts_Config(){
		
	}
	
	public static Map<String,XmlBean> parseXML(String xmlpath) throws Exception{
		
		Map<String,XmlBean> rmap = new HashMap<String, XmlBean>();
		SAXBuilder builder = new SAXBuilder();
		Document document = builder.build(new File(xmlpath));
		Element root = document.getRootElement();
		
		Element actionRoot = root.getChild("action-mappings");
		List<Element> actionList = actionRoot.getChildren();
		for(Element e : actionList ){
			XmlBean bean = new XmlBean();
			String name = e.getAttributeValue("name");
			bean.setBeanName(name);
			Element actionForm = root.getChild("formbeans");
			List<Element> form = actionForm.getChildren();
			for(Element ex : form){
				if(name.equals(ex.getAttributeValue("name"))){
					String beanClass = ex.getAttributeValue("type");
					bean.setBeanClass(beanClass);
					break;
				}
			}
			String path = e.getAttributeValue("path");
			bean.setPath(path);
			String actionClass = e.getAttributeValue("type");
			bean.setActionClass(actionClass);
			List<Element> forwardList = e.getChildren();
			Map<String,String> map = new HashMap<String, String>();
			for(Element ee : forwardList){
				String fname = ee.getAttributeValue("name");
				String fvalue = ee.getAttributeValue("value");
				map.put(fname,fvalue);
				System.out.println(map);
			}
			
			bean.setActionForward(map);
			rmap.put(path, bean);
		}
		
		return rmap;
	}
	
	
	public static void main(String arg[]) throws Exception{
//		Map<String,XmlBean> map =  new Struts_Config().parseXML();
//		Set<String> set = map.keySet();
//		for(Iterator<String> it=set.iterator();it.hasNext(); ){
//			String key = it.next();
//			System.out.println(key);
//			System.out.println(map.get(key));
//	}
	}
}
